#pragma once

#include <iostream>
using namespace std;
#include <unordered_map>
#include <functional>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>

using task_t = function<void()>;

static int number = 0;

void DownLoad()
{
    cout << "下载任务..." << "pid:" << getpid() << endl;
}
void Log()
{
    cout << "日志任务..." << "pid:" << getpid() << endl;
}
void Sql()
{
    cout << "数据库同步任务..." << "pid:" << getpid() << endl;
}
class TaskManager
{
public:
    TaskManager()
    {
        srand(time(nullptr));
        this->InsertTask(DownLoad);
        InsertTask(Log);
        InsertTask(Sql);
    }
    ~TaskManager()
    {
    }
    void InsertTask(task_t t)
    {
        tasks[number++] = t;
    }
    int SelectTask()
    {
        return rand() % number;
    }
    void Execute(int number)
    {
        if (tasks.find(number) == tasks.end())
            return;
        tasks[number]();
    }

private:
    unordered_map<int, task_t> tasks;
};

TaskManager tmp;

void Worker()
{
    while (true)
    {
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd));
        if (n == sizeof(cmd))
        {
            tmp.Execute(cmd);
            cout << "----------------------" << endl;
        }
        else if (n == 0)
        {
            cout << "pid: " << getpid() << " quit..." << endl; // 写端关闭，读端正常，读端读到0，表示读到文件末尾
            break;
        }
        else
        {
        }
    }

    // sleep(10);
}

